using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using CodePlex.Resourceful;

namespace CodePlex.SpaceBlock.UI.Controls
{
    public partial class DataGridView2 : DataGridView, ISupportDialogKeys
    {
        public event EventHandler<DialogKeyEventArgs> ProcessingDialogKey;

        private Dictionary<int, string[]> _suggestions = new Dictionary<int, string[]>();

        public DataGridView2()
        {
            InitializeComponent();
            this.Setup();
        }

        private void Setup()
        {
            this.AllowUserToAddRows = false;
            this.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            this.RowHeadersVisible = false;
            this.AllowUserToResizeRows = false;
            this.AllowUserToDeleteRows = false;

            this.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(0xf8,0xf8,0xf8);
            this.AdvancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None;


            DataGridViewColumn colImage = new DataGridViewImageColumn();
            colImage.Name = "Image";
            colImage.HeaderText = "";
            colImage.Width = 18;

            this.Columns.Add(colImage);

            this.SelectionChanged += delegate
            {

                // this should not really be here...
                IEnumerable<long> sizes = Utils.ConvertAll<DataGridViewRow,long>(this.SelectedRows, delegate(DataGridViewRow item)
                {
                    IFileItem fi = item.Tag as IFileItem;
                    return fi!=null?fi.Size:0;
                });

                long totalSize = Utils.Aggregate<long,long>(sizes, delegate(long item0, long item1)
                {
                    return item0 + item1;
                });

                string sizeString = totalSize == 0 ? "" : string.Format(" ({0})", Utils.ComputeSizeString(totalSize));

                UIManager.Instance.SetStatus("{0} object{1} selected{2}.", 
                    this.SelectedRows.Count,
                    this.SelectedRows.Count==1?"":"s",
                    sizeString);


            };

            this.MouseDown += delegate(object sender, MouseEventArgs e)
            {
             

                // force select on right-mouse-down
                if (e.Button == MouseButtons.Right)
                {
                    HitTestInfo info = this.HitTest(e.X, e.Y);
                    if (info.RowIndex > -1 && !this.Rows[info.RowIndex].Selected)
                    {
                        this.ClearSelection();
                        if (this.SelectionMode == DataGridViewSelectionMode.FullRowSelect)
                        {
                            this.SetSelectedRowCore(info.RowIndex, true);
                        }
                        if (this.SelectionMode == DataGridViewSelectionMode.CellSelect)
                        {
                            this.SetSelectedCellCore(info.ColumnIndex, info.RowIndex, true);
                        }
                    }
                }

               
                // if left-click 
                if (e.Button == MouseButtons.Left)
                {
                    HitTestInfo info = this.HitTest(e.X, e.Y);
                    if (info.RowIndex > -1 && this.SelectedRows.Count > 1 && this.Rows[info.RowIndex].Selected)
                    {
                 //       putback = this.SelectedRows;
                    }
                }

               
            };

            this.EditingControlShowing += delegate(object sender, DataGridViewEditingControlShowingEventArgs e)
            {
                DataGridViewTextBoxEditingControl text = e.Control as DataGridViewTextBoxEditingControl;


                if (text != null)
                {
                    text.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    text.AutoCompleteSource = AutoCompleteSource.CustomSource;
                    text.AutoCompleteCustomSource.AddRange(_suggestions[this.CurrentCell.ColumnIndex]);
                }

                DataGridViewComboBoxEditingControl combo = e.Control as DataGridViewComboBoxEditingControl;

               
                if (combo != null)
                {
                    combo.DropDownStyle = ComboBoxStyle.DropDown;
                   
                }
            };

        }

        public DataGridViewTextBoxColumn AddColumnText(string name, int width, params string[] suggest)
        {

            DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
            
            col.Name = name;
            col.Width = width;
            col.ReadOnly = suggest.Length == 0;
            this.Columns.Add(col);

            _suggestions.Add(col.Index, suggest);
            return col;
        }

        public DataGridViewComboBoxColumn AddColumnCombo(string name, int width, params string[] suggest)
        {

            DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();


            col.DataSource = suggest;

            col.Name = name;
            col.Width = width;
            //col.CellTemplate.FormattedValueType = typeof(string);
            col.ReadOnly = suggest.Length == 0;
            this.Columns.Add(col);

            _suggestions.Add(col.Index, suggest);
            return col;
        }


        public DataGridViewRow AddRow(object tag, params object[] values)
        {

            DataGridViewRow row = (DataGridViewRow)this.RowTemplate.Clone();

            row.CreateCells(this, values);
            row.Tag = tag;
            row.Height = 18;
            row.ReadOnly = false;

            this.Rows.Add(row);
            return row;

        }


        protected override bool ProcessDataGridViewKey(KeyEventArgs e)
        {
            if (e.KeyData == Keys.Delete)
            {
                if (ProcessingDialogKey != null)
                {
                    DialogKeyEventArgs args = new DialogKeyEventArgs(e.KeyData);

                    ProcessingDialogKey(this, args);

                }
            }
            return base.ProcessDataGridViewKey(e);
        }



        public DataGridViewProgressColumn AddProgressColumn(string name)
        {
            DataGridViewProgressColumn col = new DataGridViewProgressColumn();
            col.Name = name;
            //col.Width = width;
            //col.CellTemplate.FormattedValueType = typeof(string);
          //  col.ReadOnly = suggest.Length == 0;
            this.Columns.Add(col);

           // _suggestions.Add(col.Index, suggest);
            return col;

        }



        // adapted from http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=176890&SiteID=1

        public class DataGridViewProgressColumn : DataGridViewImageColumn
        {
            public DataGridViewProgressColumn()
            {
                CellTemplate = new DataGridViewProgressCell();
            }
        }


        class DataGridViewProgressCell : DataGridViewImageCell
        {
            // Used to make custom cell consistent with a DataGridViewImageCell
            static Image emptyImage;
            static DataGridViewProgressCell()
            {
                emptyImage = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            }
            public DataGridViewProgressCell()
            {
                this.ValueType = typeof(int);
            }
            // Method required to make the Progress Cell consistent with the default Image Cell.
            // The default Image Cell assumes an Image as a value, although the value of the Progress Cell is an int.
            protected override object GetFormattedValue(object value,
                                int rowIndex, ref DataGridViewCellStyle cellStyle,
                                TypeConverter valueTypeConverter,
                                TypeConverter formattedValueTypeConverter,
                                DataGridViewDataErrorContexts context)
            {
                return emptyImage;
            }

            protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
            {
             
                int progressVal = (int)value;
                float percentage = ((float)progressVal / 100.0f); // Need to convert to float before division; otherwise C# returns int which is 0 for anything but 100%.
                Brush backColorBrush = new SolidBrush(cellStyle.BackColor);
                Brush foreColorBrush = new SolidBrush(cellStyle.ForeColor);
                // Draws the cell grid
                base.Paint(g, clipBounds, cellBounds,
                 rowIndex, cellState, value, formattedValue, errorText,
                 cellStyle, advancedBorderStyle, (paintParts & ~DataGridViewPaintParts.ContentForeground));
                if (percentage > 0.0)
                {
                    // Draw the progress bar and the text
                    g.FillRectangle(new SolidBrush(Color.FromArgb(163, 189, 242)), cellBounds.X + 2, cellBounds.Y + 2, Convert.ToInt32((percentage * cellBounds.Width - 4)), cellBounds.Height - 4);
                 //   g.DrawString(progressVal.ToString() + "%", cellStyle.Font, foreColorBrush, cellBounds.X + 6, cellBounds.Y + 2);
                }
                else
                {
                    // draw the text
                    //if (this.DataGridView.CurrentRow.Index == rowIndex)
                    //    g.DrawString(progressVal.ToString() + "%", cellStyle.Font, new SolidBrush(cellStyle.SelectionForeColor), cellBounds.X + 6, cellBounds.Y + 2);
                    //else
                    //    g.DrawString(progressVal.ToString() + "%", cellStyle.Font, foreColorBrush, cellBounds.X + 6, cellBounds.Y + 2);
                }
            }
        }
       
     
    }
}
